package in.ac.dei.edrp.cms.daoimpl.registration.prestagingdaoimpl;
//CHANGE REG 
import java.sql.SQLException;

import in.ac.dei.edrp.cms.constants.CRConstant;
import in.ac.dei.edrp.cms.daoimpl.registration.mastertransferdaoimpl.TransferTempIntoMaster;
import in.ac.dei.edrp.cms.domain.registration.prestaging.ApplicantUserInfoBean;
import in.ac.dei.edrp.cms.domain.registration.prestaging.MasterTransferBean;
import in.ac.dei.edrp.cms.domain.registration.prestaging.ReadyPreStagingBean;
import in.ac.dei.edrp.cms.domain.registration.prestaging.TransferNORInPSTBean;
import in.ac.dei.edrp.cms.domain.registration.prestaging.TransferPSTRDYInSTBean;
import in.ac.dei.edrp.cms.domain.utility.EmailTableBean;
import in.ac.dei.edrp.cms.domain.utility.StudentTracking;
import in.ac.dei.edrp.cms.utility.CRException;
import in.ac.dei.edrp.cms.utility.ReadyPreStaging;
import in.ac.dei.edrp.cms.utility.StudentTrackingFunction;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.ibatis.sqlmap.client.SqlMapClient;

public class PreStagingTransactionFunction{
	
	static final Logger logger = Logger.getLogger(PreStagingTransactionFunction.class);
	
	private TransactionTemplate transactionTemplate=null;
	
	public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
		this.transactionTemplate = transactionTemplate;
	}

	protected SqlMapClient sqlMapClient = null;
	
    public void setSqlMapClient(SqlMapClient sqlMapClient) {
        this.sqlMapClient = sqlMapClient;
    }

    public PreStagingTransactionFunction(SqlMapClient sqlMapClient,TransactionTemplate transactionTemplate){
    	this.sqlMapClient=sqlMapClient;
    	this.transactionTemplate=transactionTemplate;
    }
    
    public PreStagingTransactionFunction(){
    	
    }
    
	/**
	 * This method executes following query:
	 * 1- Insert student in staging_table
	 * 2- Update process_status by PRC in pre staging table 
	 * 3- Insert student in Applicant Info
	 * 4- If transaction is successful, it calls function to send mail
	 * @param objectToTransferInST: It contains full information of a student from prestaging table.
	 * It is inserted into staging table 
	 * @param objectForUpdatePST: This object updates status by PRC.
	 * @param objectToInsertInAI: This object is inserted into Applicant_Info
	 * @return
	 */
	public void insertStudentInStaging(final TransferPSTRDYInSTBean objectToTransferInST,
											final TransferPSTRDYInSTBean objectForUpdatePST,
											final ApplicantUserInfoBean objectToInsertInAI,
											final EmailTableBean emailTableBean){
		
		transactionTemplate.execute(new TransactionCallbackWithoutResult(){
			//Object savepoint=null;
		
			@Override
			public void doInTransactionWithoutResult(TransactionStatus status) {
			try{
				//insert student in staging_table
				sqlMapClient.insert("TransferPSTRDYInST.insertStudentInST",objectToTransferInST);
				//update process_status of student in PreStaging_table
				sqlMapClient.update("TransferPSTRDYInST.updateStudentInPST",objectForUpdatePST);
				//insert student in Applicant_Info
				if(objectToTransferInST.getAdmissionMode().equalsIgnoreCase(CRConstant.NORMAL_MODE)||
						objectToTransferInST.getAdmissionMode().equalsIgnoreCase(CRConstant.SWITCH_MODE)){
					System.out.println("Inserting student inside applicant info");
				sqlMapClient.insert("TransferPSTRDYInST.insertInApplicantInfo", objectToInsertInAI);
				}
				else{
					if(objectToTransferInST.getAdmissionMode().equalsIgnoreCase(CRConstant.NEW_MODE)){
						sqlMapClient.insert("emailTable.insertIntoEMailTable", emailTableBean);
					}
				}
				
				
			}catch(DataAccessException e){
//				System.out.println("before save anil inside data access="+status.isNewTransaction());
				System.out.println("Exception coming"+e.getMessage());
				status.setRollbackOnly();
				
				throw new CRException("invalid student.Roll Number :"+objectToTransferInST.getRollNumber());
					} catch (Exception e) {
						System.out.println("Exception comingdsa"+e.getMessage());
						status.setRollbackOnly();
				// TODO Auto-generated catch block
//				e.printStackTrace();
			}
			}//
	
        });
		
}

	
	/**
	 * This method executes following query:
	 * 1- Insert Student with Pass and Fail status in prestaging_table
	 * 2- Insert student with status YTR in student registration semester header 
	 * 3- Update student process status by LRG in student registration semester header
	 * @param passOrFailPSTData: Object contains full details which is required to insert in PreStaging table
	 */
	public void executeQueryForPreStaging(final TransferNORInPSTBean passOrFailPSTData){
		//Connection con=DBConnection.getConnection();
	
		transactionTemplate.execute(new TransactionCallbackWithoutResult(){
			//Object savepoint=null;
		
			@Override
			public void doInTransactionWithoutResult(TransactionStatus status) {
			try{
				//Insert suudent with its status in semester either PASS/FAIL
			sqlMapClient.update("TransferNORInPSTBean.insertPSTPassOrFail", passOrFailPSTData);
			//Insert student with YTR into SRSH
			sqlMapClient.update("TransferNORInPSTBean.insertSRSHWithYTR", passOrFailPSTData);
			//Update student process status with LRG into SRSH			
			sqlMapClient.update("TransferNORInPSTBean.updateSRSHWithLRG", passOrFailPSTData);
			
			StudentTracking studentTracking=new StudentTracking(passOrFailPSTData.getEntityId(),passOrFailPSTData.getRollNumber(),
					passOrFailPSTData.getNextProgramCourseKey(),passOrFailPSTData.getNextSemesterStartDate(),passOrFailPSTData.getNextSemesterEndDate(),
					passOrFailPSTData.getSessionStartDate(),passOrFailPSTData.getSessionEndDate(),CRConstant.YET_TO_REGISTER,
					CRConstant.ACTIVE_STATUS,passOrFailPSTData.getCreatorId(),passOrFailPSTData.getActivityId(),"REG");
			int sequence=new StudentTrackingFunction(sqlMapClient,transactionTemplate).getStdentTrackingIssue(studentTracking);
			
			studentTracking.setSequenceNumber(sequence+1);
			//Insert a student in student tracking with semester status YTR and program status ACT
			sqlMapClient.update("studentTrackingAndLogs.insertStudentTracking", studentTracking);

			}catch(DataAccessException e){
//				System.out.println("before save anil inside data access="+status.isNewTransaction());
				// Set transaction status to rollback
				//	status.rollbackToSavepoint(savepoint);
					status.setRollbackOnly();
				throw new CRException("invalid update to student");
					} catch (Exception e) {
				// TODO Auto-generated catch block
				status.setRollbackOnly();
//				e.printStackTrace();
			}
			}//
	
        });
	}
	
	/**
	 	* This method executes following query:
		* 1- Insert Student with Pass and Fail status in prestaging_table
		* 2- Insert student with status YTR in student registration semester header 
		* 3- Update student process status by LRG in student registration semester header
		*@param remedialPSTData: student having REM status with its full details
	 */
	public void executeQueryForRemedialPreStaging(final TransferNORInPSTBean remedialPSTData){
		
	
		transactionTemplate.execute(new TransactionCallbackWithoutResult(){
			//Object savepoint=null;
		
			@Override
			public void doInTransactionWithoutResult(TransactionStatus status) {
			try{
				//Insert student having status REM in prestaging
			sqlMapClient.update("TransferNORInPSTBean.insertPSTRemedial", remedialPSTData);
			//Insert student with YTR into SRSH
			int insertSRSH=sqlMapClient.update("TransferNORInPSTBean.insertSRSHWithYTR", remedialPSTData);
			//Update student process status with LRG into SRSH			s			
			int updateSRSH=sqlMapClient.update("TransferNORInPSTBean.updateSRSHWithLRG", remedialPSTData);
			
			StudentTracking studentTracking=new StudentTracking(remedialPSTData.getEntityId(),remedialPSTData.getRollNumber(),
					remedialPSTData.getNextProgramCourseKey(),remedialPSTData.getNextSemesterStartDate(),remedialPSTData.getNextSemesterEndDate(),
					remedialPSTData.getSessionStartDate(),remedialPSTData.getSessionEndDate(),CRConstant.YET_TO_REGISTER,
					CRConstant.ACTIVE_STATUS,remedialPSTData.getCreatorId(),remedialPSTData.getActivityId(),"REG");
			int sequence=new StudentTrackingFunction(sqlMapClient,transactionTemplate).getStdentTrackingIssue(studentTracking);
			
			studentTracking.setSequenceNumber(sequence+1);
			//Insert a student in student tracking with semester status YTR and program status ACT
			int insertST=sqlMapClient.update("studentTrackingAndLogs.insertStudentTracking", studentTracking);
			
			
			}catch(DataAccessException e){
//				System.out.println("before save anil inside data access="+status.isNewTransaction());
				// Set transaction status to rollback
				status.setRollbackOnly();
				throw new CRException("invalid update to student");
					} catch (Exception e) {
				// TODO Auto-generated catch block
				status.setRollbackOnly();
				//e.printStackTrace();
			}
			}//
	
        });
	}
	
	/**
	 * 
	 * @param updateNormalWithSwitch
	 * @param updateSwitchWithNormal
	 * @param updateSRSH
	 * @param b
	 * @return
	 */
	public boolean insertNORWithSWTInPST(final ReadyPreStagingBean updateNormalWithSwitch,
	final ReadyPreStagingBean updateSwitchWithNormal,final ReadyPreStagingBean updateSRSH,final boolean b){
		
		try{
		transactionTemplate.execute(new TransactionCallbackWithoutResult(){
			//Object savepoint=null;
			ReadyPreStaging readyPreStaging=new ReadyPreStaging(sqlMapClient,transactionTemplate);
			@Override
			public void doInTransactionWithoutResult(TransactionStatus status) {
			try{
				
				sqlMapClient.update("MakeStatusReadyPreStaging.updatePSTReasonAndStatus",updateNormalWithSwitch);
				
				sqlMapClient.update("MakeStatusReadyPreStaging.updatePSTReasonAndStatus",updateSwitchWithNormal);
				
				if(b==true){
			
				sqlMapClient.update("updateSRSHStatus",updateSRSH);
				StudentTracking studentTracking=new StudentTracking(updateNormalWithSwitch.getEntityId(),updateNormalWithSwitch.getRollNumber(),
						updateNormalWithSwitch.getProgramCourseKey(),updateNormalWithSwitch.getSemesterStartDate(),updateNormalWithSwitch.getSemesterEndDate(),
						updateNormalWithSwitch.getSessionStartDate(),updateNormalWithSwitch.getSessionEndDate(),CRConstant.INACTIVE_STATUS,
						CRConstant.ACTIVE_STATUS,updateNormalWithSwitch.getModifierId(),updateNormalWithSwitch.getActivityId(),"REG");
				int sequence=new StudentTrackingFunction(sqlMapClient,transactionTemplate).getStdentTrackingIssue(studentTracking);
				
				studentTracking.setSequenceNumber(sequence+1);
				sqlMapClient.update("studentTrackingAndLogs.insertStudentTracking", studentTracking);
				
				studentTracking=new StudentTracking(updateSwitchWithNormal.getEntityId(),updateSwitchWithNormal.getRollNumber(),
						updateSwitchWithNormal.getProgramCourseKey(),updateSwitchWithNormal.getSemesterStartDate(),updateSwitchWithNormal.getSemesterEndDate(),
						updateSwitchWithNormal.getSessionStartDate(),updateSwitchWithNormal.getSessionEndDate(),CRConstant.YET_TO_REGISTER,
						CRConstant.ACTIVE_STATUS,updateSwitchWithNormal.getModifierId(),updateSwitchWithNormal.getActivityId(),"REG");
				sequence=new StudentTrackingFunction(sqlMapClient,transactionTemplate).getStdentTrackingIssue(studentTracking);
				
				studentTracking.setSequenceNumber(sequence+1);
				sqlMapClient.update("studentTrackingAndLogs.insertStudentTracking", studentTracking);
			}
					
			}catch(DataAccessException e){
//				System.out.println("before save anil inside data access="+status.isNewTransaction());
				status.setRollbackOnly();
				throw new CRException("invalid student.Roll Number :"+updateNormalWithSwitch.getRollNumber());
					} catch (Exception e) {
				// TODO Auto-generated catch block
				status.setRollbackOnly();
				//e.printStackTrace();
			}
			}//
	
        });
		return true;
	}catch(Exception e){
		System.out.println("Exception inside NOR and SWITCH "+e.getMessage());
		return false;
	}
		
	
	}
}
